<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>聊天室</title>
  <style>
    #ul1 {
      border: 1px solid #333;
      width: 460px;
      height: 300px;
      overflow: auto;
    }

    .me {
      color: green;
      text-align: right;

    }

    .err_msg {
      width: 500px;
      height: 50px;
      line-height: 50px;
      color: red;
      text-align: center;
    }
  </style>
  <script src="http://localhost:8007/socket.io/socket.io.js" charset="utf-8"></script>
  <script>
    let sock = io.connect('ws://localhost:8007/')

    //判断是否连接到服务器
    sock.on('connect', () => {
      console.log('连接了');
      document.getElementsByClassName('err_msg')[0].style.display = 'none'
    })
    sock.on('disconnect', () => {
      console.log('断开了');
      document.getElementsByClassName('err_msg')[0].style.display = 'block'
    })

    //聊天室
    window.onload = function () {
      let oTxt = document.getElementById('txt1');
      let oBtn = document.getElementById('btn1')
      let oUl = document.getElementById('ul1')

      oBtn.onclick = function () {
        sock.emit('msg', oTxt.value);

        let oLi = document.createElement('li')
        oLi.innerHTML = oTxt.value;
        oLi.className = 'me'
        oUl.appendChild(oLi)

        oTxt.value = '';


      }

      sock.on('msg', str => {
        let oLi = document.createElement('li')
        oLi.innerHTML = str;
        oUl.appendChild(oLi)
      })


    }

  </script>
</head>

<body>
  <div class="err_msg">
    无法连接到服务器，请检查网络
  </div>
  <ul id="ul1"></ul>
  <textarea name="main" id="txt1" cols="80" rows="5"></textarea>
  <br>
  <button id="btn1">发送</button>

</body>

</html>